#include "stm32f10x.h"                  // Device header
#include "Timer.h"

void Timer_Init(void)
{
	
	//Setp 1.
	//RCC APB1的外设时钟控制，因为TIM2在STM32的APB1外设总线上
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
	
	//GPIO初始化
	//开启GPIO外设时钟
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
	GPIO_InitTypeDef GPIO_InitStruct;
	GPIO_InitStruct.GPIO_Mode = GPIO_Mode_IPU;		//上拉输入
	GPIO_InitStruct.GPIO_Pin = GPIO_Pin_0;
	GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOA, &GPIO_InitStruct);
	
	//Setp 2.
	//选择时基单元的时钟，使用内部RCC时钟 CLK_INT (Clock_Internal)
	//TIM_InternalClockConfig(TIM2);
	
	//选择时基单元的时钟，使用外部时钟ETR mode2
	TIM_ETRClockMode2Config(TIM2, TIM_ExtTRGPSC_OFF, TIM_ExtTRGPolarity_NonInverted, 0x0f);
	
	
	//Setp 3.
	//配置时基单元
	TIM_TimeBaseInitTypeDef TimeBaseInitStruct;
	TimeBaseInitStruct.TIM_ClockDivision = TIM_CKD_DIV1;		//时钟信号滤波使用，滤波的采样频率，采样点数
	TimeBaseInitStruct.TIM_CounterMode = TIM_CounterMode_Up;	//计数器向上计数
	TimeBaseInitStruct.TIM_Period = 10 - 1;						//Auto-Reload Register 自动重装载寄存器的值，记得需要减一
	TimeBaseInitStruct.TIM_Prescaler = 1 - 1;					//预分频器的值，记得需要减一
	TimeBaseInitStruct.TIM_RepetitionCounter = 0;				//重复计数器的值	
	TIM_TimeBaseInit(TIM2, &TimeBaseInitStruct);
	
	
	//在TIM_TimeBaseInit()之后，在启用中断之前，手动清除一下定时器更新中断标志位，
	//就能避免初始化之后就立即进入中断的问题了。
	TIM_ClearITPendingBit(TIM2, TIM_IT_Update);
	
	//Setp 4.
	//使能定时中断
	TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE);
	
	//Setp 5.
	//NVIC配置
	NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);	//NVIC优先级分组
	
	NVIC_InitTypeDef NVIC_InitStruct;
	NVIC_InitStruct.NVIC_IRQChannel = TIM2_IRQn;
	NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE;
	NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 2;
	NVIC_InitStruct.NVIC_IRQChannelSubPriority = 1;
	NVIC_Init(&NVIC_InitStruct);					//NVIC配置定时器中断优先级
	
	
	//Setp 6.
	//定时器启动
	TIM_Cmd(TIM2, ENABLE);
}


uint16_t Num;

//定时器TIM2，中断处理函数
void TIM2_IRQHandler(void)
{
	//检查中断标志位
	if(SET == TIM_GetITStatus(TIM2, TIM_IT_Update))
	{
		Num++;
		
		//清除中断标志位
		TIM_ClearITPendingBit(TIM2, TIM_IT_Update);
	}
}
